app.controller('ChatCtrl', ['$scope', '$interpolate', '$http', 'socket', function ($scope, $interpolate, $http, socket) {
	
	var templates = {
			'join' : '<div class="join"><p class="time">{{message.joinTime}}</p><div class="avatar {{user.avatarClass}}" ng-if="user.avatarClass"></div>User {{user.name | sanitize}} has joined</div>',
			'leave' : '<div class="leave"><p class="time">{{time}}</p><div class="avatar {{user.avatarClass}}" ng-if="user.avatarClass"></div>User {{user.name | sanitize}} has left</div>',
			'chat' : '<div class="chat"><p class="time">{{time}}</p><div><div class="avatar {{user.avatarClass}}" ng-if="user.avatarClass"></div>{{user.name | sanitize}}</div><pre>{{message.message | sanitize | linky:\'_blank\'}}</pre></div>',
			'mychat' : '<div class="mychat"><p class="time">{{time}}</p><pre>{{message.message | sanitize | linky:\'_blank\'}}</pre><div><div class="avatar {{user.avatarClass}}" ng-if="user.avatarClass"></div>{{user.name | sanitize}}</div></div>'
	},
	recentDataStr = localStorage['recentData'],
	recentData = (recentDataStr) ? JSON.parse(recentDataStr) : {};
	
	$scope.avatarList = {};
	$scope.avatarKeys = [];
	$scope.req = {
		name : recentData.name,
		fname : recentData.fullName,
		avatar : recentData.avatarClass,
		room : recentData.room
	};
	$scope.name = null;
	$scope.fullName = null;
	$scope.room = null;
	$scope.messages = [];
	$scope.glued = true;
	$scope.avatarURI = null;
	$scope.users = [];
	$scope.userMap = {};
	$scope.chatText = '';
	
	$http.get('includes/js/avatars.json').success(function(response) {
		$scope.avatarList = response;
		$scope.avatarKeys = Object.keys(response);
	});
	
	$scope.send = function() {
		if($scope.chatText) {
			socket.sendMessage({ type: 'chat', message: $scope.chatText });
			$scope.chatText = '';
		}
	};
	
	$scope.submit = function($event) {
		if($event.keyCode === 13 && !$event.shiftKey) {
			$scope.send();
			$event.preventDefault();
		}
	};
	
	$scope.joinRoom = function() {
		var curUser;
		$scope.fullName = $scope.req.fname;
		$scope.name = $scope.req.name;
		$scope.room = $scope.req.room;
		$scope.avatarClass = $scope.req.avatar;
		curUser = {
			name : $scope.name,
			avatarClass : $scope.avatarClass,
			fullName : $scope.fullName,
			room : $scope.room
		};
		localStorage['recentData'] = JSON.stringify(curUser);
		$scope.userMap[$scope.name] = curUser;
		
		socket.connect();
		
		socket.onopen(function(message) {
			socket.sendMessage({ name : $scope.name, fullName: $scope.fullName, room: $scope.room, avatarClass: $scope.avatarClass, type: 'join' });
		});
		
		socket.onmessage('join', function(message) {
			$scope.users.push(message);
			$scope.userMap[message.name] = {
				name : message.name,
				avatarClass : message.avatarClass,
				fullName : message.fullName
			};
			message.joinTime = new Date(message.joinTime).format('hh:mm:ss');
			storeMessage(message);
		});
		
		socket.onmessage('leave', function(message) {
			storeMessage(message);
			var remove = -1;
			for(var i = 0; i < $scope.users.length; i++) {
				if($scope.users[i].name === message.name) {
					remove = i;
				}
			}
			if(remove > -1) {
				$scope.users.splice(remove, 1);
				if($scope.userMap[message.name]) {
					delete $scope.userMap[message.name];
				}
			}
		});
		
		socket.onmessage('chat', function(message) {
			storeMessage(message);
		});
	};
	
	$scope.handleMessages = function(messages) {
		var exp, messageAr = []; 
		for(var i = 0; i < messages.length; i++) {
			exp = $interpolate(templates[messages[i].type]);
			messageAr.push(exp({ message : messages[i], user : messages[i].$user, time: messages[i].$time }));
		}
		return messageAr;
	};
	
	function storeMessage(message) {
		if('chat' === message.type && $scope.name === message.name) {
			message.type = 'mychat';
		}
		message.$user = $scope.userMap[message.name];
		message.$time = new Date().format('hh:mm:ss');
		$scope.messages.push(message);
	}
	
}]);